// pages/operation_interface/operation_interface_test.js
var mqtt = require('../../utils/mqtt.min.js') //根据自己存放的路径修改 加载mqtt.min.js这个模块
const crypto = require('../../utils/hex_hmac_sha1.js'); //根据自己存放的路径修改 加载hmac_sha1.js这个模块

//var keep_connect;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    switch1Checked:false,
    switch2Checked:false,
    slidervalue:0,
    slidervalue1:0,
    // array: ['美国', '中国', '巴西', '日本'],
    // index:0,
  },

switch1Change:function(event)
{
  //console.log(event.detail);
  // mqtt.publish('presence', 'Hello mqtt');
  if(event.detail.value == false)
  {
    var b = this.changeHumidified(0);
  }
  else if(event.detail.value == true)
  {
    var b = this.changeHumidified(1);
  }
  
  this.data.switch1Checked = event.detail.value;
  console.log(b);

  //console.log("按键函数:",this.data.switch1Checked);
  
  getApp().globalData.keep_connect.publish('/sys/a1ay7f9DL7I/Applet_test/thing/event/property/post', b);
},


  switch2Change:function(event)
  {
    //console.log(event.detail);
    if(event.detail.value == false)
    {
      var b = this.changeFanSwitch(0);
    }
    else if(event.detail.value == true)
    {
      var b = this.changeFanSwitch(1);
    }
    
    console.log(b);

    this.data.switch2Checked = event.detail.value;

    //console.log("按键函数",this.data.switch2Checked);

    getApp().globalData.keep_connect.publish('/sys/a1ay7f9DL7I/Applet_test/thing/event/property/post', b);
  },

  changeFanSwitch(status)
  {
    var a = "{\"id\":\"ESP8266\",\"version\":\"1.0\",\"method\":\"thing.event.property.post\",\"params\":%s}"

    if(status == 0)
    {
      var b = a.replace("%s", "{\"FanSwitch\":{\"value\":0}}");
    }
    else if(status == 1)
    {
      var b = a.replace("%s", "{\"FanSwitch\":{\"value\":1}}");
    }

    return b;
  },

  changeHumidified(status)
  {
    var a = "{\"id\":\"ESP8266\",\"version\":\"1.0\",\"method\":\"thing.event.property.post\",\"params\":%s}"
    
    
    if(status == 0)
    {
      var b = a.replace("%s", "{\"Humidified\":{\"value\":0}}");
    }
    else if(status == 1)
    {
      var b = a.replace("%s", "{\"Humidified\":{\"value\":1}}");
    }

    return b;
  },

  sliderchange(event)
  {
    //console.log(event.detail.value);
    var a =  "{\"id\":\"ESP8266\",\"version\":\"1.0\",\"method\":\"thing.event.property.post\",\"params\":%s}";

    if(event.detail.value == 1)
    {
      var b = a.replace("%s", "{\"WS2812B_Color\":{\"value\":1}}");
    }
    else if(event.detail.value == 2)
    {
      var b = a.replace("%s", "{\"WS2812B_Color\":{\"value\":2}}");
    }
    else if(event.detail.value == 3)
    {
      var b = a.replace("%s", "{\"WS2812B_Color\":{\"value\":3}}");
    }
    else if(event.detail.value == 4)
    {
      var b = a.replace("%s", "{\"WS2812B_Color\":{\"value\":4}}");
    }
    else if(event.detail.value == 5)
    {
      var b = a.replace("%s", "{\"WS2812B_Color\":{\"value\":5}}");
    }
    else if(event.detail.value == 6)
    {
      var b = a.replace("%s", "{\"WS2812B_Color\":{\"value\":6}}");
    }
    else if(event.detail.value == 7)
    {
      var b = a.replace("%s", "{\"WS2812B_Color\":{\"value\":7}}");
    }
    else if(event.detail.value == 8)
    {
      var b = a.replace("%s", "{\"WS2812B_Color\":{\"value\":8}}");
    }
    else if(event.detail.value == 0)
    {
      var b = a.replace("%s", "{\"WS2812B_Color\":{\"value\":0}}");
    }

    console.log(b);

    this.data.slidervalue = event.detail.value;

    console.log(this.data.slidervalue);

    getApp().globalData.keep_connect.publish('/sys/a1ay7f9DL7I/Applet_test/thing/event/property/post', b);
  },

  sliderchange1(event)
  {
    console.log(event.detail.value);
    var a =  "{\"id\":\"ESP8266\",\"version\":\"1.0\",\"method\":\"thing.event.property.post\",\"params\":%s}";
    var b = event.detail.value.toString();
    console.log(b);
    var c = a.replace("%s", "{\"WS2812B_brightness\":{\"value\":%s}}");
    var d = c.replace("%s", b);
    
    console.log(d);

    this.data.slidervalue1 = event.detail.value;
    
    console.log(this.data.slidervalue1);

    getApp().globalData.keep_connect.publish('/sys/a1ay7f9DL7I/Applet_test/thing/event/property/post', d);
  },
  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // if(getApp().globalData.connect_flag == false)
    // {
    //   this.ConnectToAliyun(0);
    // }

    // console.log("interface onLoad:",getApp().globalData.connect_flag);
  

    //console.log("OnLoad",this.data.switch1Checked);
    //console.log("Onload",this.data.switch2Checked);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;

    // console.log("interrface_test onShow:", getApp().globalData.connect_flag);
    // if(getApp().globalData.connect_flag == false)
    // {
    //   this.ConnectToAliyun(0);
    // }

   
    getApp().globalData.keep_connect.on('message',function(topic, message)
    {
      var msg = message.toString();
      //console.log(msg);
  
      if(msg.indexOf("fan") != -1)
      {
        if(msg[7] == 1)
        {
          that.setData({switch2Checked:true});
        }
        else if(msg[7] == 0)
        {
          that.setData({switch2Checked:false});
        }
      }

      if(msg.indexOf("atomizer") != -1)
      {
        if(msg[12] == 1)
        {
          that.setData({switch1Checked:true});
        }
        else if(msg[12] == 0)
        {
          that.setData({switch1Checked:false});
        }
      }

      if(msg.indexOf("color") != -1)
      {
        //console.log(msg);
        if(msg[9] == 0)
        {
          that.setData({slidervalue:0});
        }
        else if(msg[9] == 1)
        {
          that.setData({slidervalue:1});
        }
        else if(msg[9] == 2)
        {
          that.setData({slidervalue:2});
        }
        else if(msg[9] == 3)
        {
          that.setData({slidervalue:3});
        }
        else if(msg[9] == 4)
        {
          that.setData({slidervalue:4});
        }
        else if(msg[9] == 5)
        {
          that.setData({slidervalue:5});
        }
        else if(msg[9] == 6)
        {
          that.setData({slidervalue:6});
        }
        else if(msg[9] == 7)
        {
          that.setData({slidervalue:7});
        }
        else if(msg[9] == 8)
        {
          that.setData({slidervalue:8});
        }
      }
    });
   
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    //getApp().globalData.keep_connect.end();
    //console.log("断开连接成功!\r\n");
    getApp().globalData.connect_flag = false;
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

ConnectToAliyun(flag)
{
  console.log("interface_test ConnectToAliyun:",getApp().globalData.connect_flag);

  getApp().globalData.connect_flag = true;
 
  const deviceConfig = 
  {
    productKey: "a1ay7f9DL7I",
    deviceName: "Applet_test",
    deviceSecret: "dd77391750a0684818fccb881c3bf28a",
    regionId: "cn-shanghai"//根据自己的区域替换
  };//只读变量

  const options = this.initMqttOptions(deviceConfig);
  console.log(options)
    
  //替换productKey为你自己的产品的（注意这里是wxs，不是wss，否则你可能会碰到ws不是构造函数的错误）
   //注意：订阅主题，替换productKey和deviceName(这里的主题可能会不一样，具体请查看控制台-产品详情-Topic 类列表下的可订阅主题)
  //const client = mqtt.connect('wxs://a1ay7f9DL7I.iot-as-mqtt.cn-shanghai.aliyuncs.com',options);

  getApp().globalData.keep_connect = mqtt.connect('wxs://a1ay7f9DL7I.iot-as-mqtt.cn-shanghai.aliyuncs.com',options);
  

  getApp().globalData.keep_connect.on('connect', function () 
  {
    if(flag == 1)
    {
      wx.showToast({
        title: '连接服务器成功',
        icon:'none'
      });
    }
   
    
    getApp().globalData.keep_connect.subscribe('/a1ay7f9DL7I/Applet_test/user/get', function (err) 
    {
      if (!err) 
      {
        if(flag == 1)
        {
          setTimeout(function(){
            wx.showToast({
              title: '订阅成功',
              icon:'none'
            });
          }, 100);
        }
      }
    })
  });
},

  //IoT平台mqtt连接参数初始化
  initMqttOptions(deviceConfig) {

    const params = {
      productKey: deviceConfig.productKey,
      deviceName: deviceConfig.deviceName,
      timestamp: Date.now(),
      clientId: Math.random().toString(36).substr(2),
    }
    //CONNECT参数
    const options = {
      keepalive: 60, //60s
      clean: true, //cleanSession不保持持久会话
      protocolVersion: 4 //MQTT v3.1.1
    }
    //1.生成clientId，username，password
    options.password = this.signHmacSha1(params, deviceConfig.deviceSecret);
    options.clientId = `${params.clientId}|securemode=2,signmethod=hmacsha1,timestamp=${params.timestamp}|`;
    options.username = `${params.deviceName}&${params.productKey}`;

    return options;
  },

/*
  生成基于HmacSha1的password
  参考文档：https://help.aliyun.com/document_detail/73742.html?#h2-url-1
*/
  signHmacSha1(params, deviceSecret){

    let keys = Object.keys(params).sort();
    // 按字典序排序
    keys = keys.sort();
    const list = [];
    keys.map((key) => {
      list.push(`${key}${params[key]}`);
    });
    const contentStr = list.join('');
    return crypto.hex_hmac_sha1(deviceSecret, contentStr);
  },

})

